package com.atguigu.tingshu.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;




    /**
     * 根据专辑ID查询专辑详情相关数据
     * @param albumId 专辑id
     * @return
     */
    @Override
    public JSONObject getItmInfo(Long albumId) {

        JSONObject map = new JSONObject();

        //1.专辑基本信息
        //有返回值
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            map.put("albumInfo",albumInfo);
            return albumInfo;
        }, threadPoolExecutor);

        //用户信息
        CompletableFuture<Void> voidCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            map.put("announcer",userInfoVo);
        }, threadPoolExecutor);

        //3.根据三级分类的id查询1 2 3级信息
        //没有返回值
        CompletableFuture<Void> voidCompletableFuture1 = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            map.put("baseCategoryView",baseCategoryView);
            }, threadPoolExecutor);

        //4.根据专辑ID获取专辑统计信息
        //没有返回 不需要前置条件
        CompletableFuture<Void> voidCompletableFuture2 = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            map.put("albumStatVo",albumStatVo);
        }, threadPoolExecutor);

        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                voidCompletableFuture,
                voidCompletableFuture1,
                voidCompletableFuture2).join();


        return map;
    }
}
